import json
from pathlib import Path

class ConfigManager:
    def __init__(self):
        self.config_path = Path('model_config.json')
        self._cached_options = None  # 新增缓存变量
        self.current_model = None  # 新增当前模型属性
        self.model_handlers = {
            '百炼平台-dkr1': 'BlPtHandler',
            'diff_ollama_dkr1': 'DiffOllamaDkr1Handler',
            'ollama_dkr1': 'OllamaDkr1Handler',
            'kouzi':'KouZiHanler'
            # 可以继续添加其他模型映射
        }

    def load_model_options(self):
        if self._cached_options is not None:  # 如果缓存存在直接返回
            return self._cached_options
            
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self._cached_options = json.load(f)  # 加载数据到缓存
                return self._cached_options
        except FileNotFoundError:
            print("file not found")
            self._cached_options = [{  # 默认配置也存入缓存
                "value": "gpt-4",
                "label": "GPT-4",
                "apiKey": "",
                "endpoint": "",
                "params": {}
            }]
            return self._cached_options

    def save_model_options(self, options):
        with open(self.config_path, 'w', encoding='utf-8') as f:
            json.dump(options, f, indent=2, ensure_ascii=False)
        self._cached_options = options  # 保存时更新缓存

    # 新增方法：获取指定模型配置
    def get_model_config(self, model_value):
        if self._cached_options is None:
            self.load_model_options()
            
        for model in self._cached_options:
            if model['value'] == model_value:
                return model
        return None

    def set_current_model(self, model_value):
        self.current_model = model_value
        return True
    
    def get_model_handler_name(self, model_value):
        """获取模型对应的处理器类名"""
        return self.model_handlers.get(model_value)
# 在初始化时创建实例并暴露方法
config_manager = ConfigManager()

def init_config_manager(window):
    window.expose(
        config_manager.load_model_options,
        config_manager.save_model_options,
        config_manager.set_current_model  # 暴露新方法
    )
    return config_manager